﻿#include "QNBLogin.h"
#include "ui_QNBLogin.h"

#include <QKeyEvent>
#include <QMessageBox>
#include <Windows.h>
#ifndef PSAPI_VERSION
#define PSAPI_VERSION  1
#endif
#include <Tlhelp32.h>
#include <Psapi.h>
#include <QFile>
#include <QDebug>
#include <QBuffer>
#include <QNetworkRequest>

#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonValue>
#include <QTimer>
#include <QThread>
#include <QPalette>
#include <QPainter>
#include <QShortcut>

#include "QNBUtls.h"
#include "QNBUserInfo.h"
#include "QNBLockCtrlAltDel.h"

#ifndef _WINXP
#include <QCameraInfo>
#endif

//#include "JQZopfli.h"

//added by xuhongneng @20170822
#pragma execution_character_set("utf-8")
#pragma comment(lib, "Psapi.lib")
//added by xuhongneng @20170822 end

void setHook();
void unHook();

//在注册表该目录下增加新内容
#define TASKMANAGER "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"

//removed by xuhongneng @20170811 begin
#define HIDE_KEY 1
//removed by xuhongneng @20170811 end

//modified by xuhongneng @20170822 begin
#define PASS_CHECK_PHOTO_DEBUG 1
//#define PASS_CHECK_PHOTO_DEBUG 0
//modified by xuhongneng @20170822 end

//modified by xuhongneng @20170824 begin
#define PROTECT_INVOKE_YES 1
//modified by xuhongneng @20170824 end

QNBLogin *QNBLogin::m_sgLogin = NULL;
QNBLogin *QNBLogin::getInstance()
{
    if (m_sgLogin == NULL) {
        m_sgLogin = new QNBLogin();
    }

    return m_sgLogin;
}

void QNBLogin::clearResource()
{
    if(m_sgLogin != NULL) {
        delete m_sgLogin;
        m_sgLogin = NULL;
    }

}

QNBLogin::QNBLogin(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QNBLogin)
{
    ui->setupUi(this);

    bCheckPhotoRunning = false;

    m_translator = new QTranslator();
    InitUiByLanguage("zh");

    //test
    if (!QNBUserInfo::getInstance()->mstrIdentify.isEmpty()) {
        ui->leIentify->setText(QNBUserInfo::getInstance()->mstrIdentify);
    }

#if HIDE_KEY
    setHook();
#endif

    m_bVerifying = false;

    mstrIdentify = "";
    mstrCapPhoto = "";

    reply = NULL;
    reply2 = NULL;
    reply3 = NULL;
    reply4 = NULL;
    //added by xuhongneng @20170825 begin
    m_pCheckDaemonProcessTimer = NULL;
    m_pVideoItem = NULL;
    m_pScence = NULL;
    m_pGraphicsView = NULL;
 #ifdef _WINXP
    m_pCamera = NULL;
    m_pCaptureToVideoTimer = NULL;
 #else
    m_pCaptureVideoFrame = NULL;
    camera = NULL;
    imageCapture = NULL;
 #endif
    //added by xuhongneng @20170825 end

    m_pCheckPhotoExe = new QProcess();
    connect(m_pCheckPhotoExe, SIGNAL(finished(int)), this, SLOT(readCheckPhotoResult(int)));

    m_pCheckPhotoByIntervalTimer = new QTimer();
    connect(m_pCheckPhotoByIntervalTimer, SIGNAL(timeout()), this, SLOT(checkPhotoByInterval()));

    m_pSubmitPhotoByIntervalTimer = new QTimer();
    connect(m_pSubmitPhotoByIntervalTimer, SIGNAL(timeout()), this, SLOT(submitPhotoByInterval()));

    m_pCheckStatusTimer = new QTimer;
    connect(m_pCheckStatusTimer, SIGNAL(timeout()), this, SLOT(checkRunningStatus()));
    m_pCheckStatusTimer->start(QNBConfig::getInstance()->loopCheckLoginStatusInterval()*1000);

 #if PROTECT_INVOKE_YES
    m_pCheckDaemonProcessTimer = new QTimer;
    connect(m_pCheckDaemonProcessTimer, SIGNAL(timeout()), this, SLOT(checkNetBarDaemonExist()));
    m_pCheckDaemonProcessTimer->start(20);
#endif

    m_heart = new QNBHeartThread;
    m_heart->setTimer();

    reqLogin = new QNetworkAccessManager(this);
    connect(reqLogin,SIGNAL(finished(QNetworkReply*)),SLOT(replyFinished(QNetworkReply*)));

    reqSaveAuthPhoto = new QNetworkAccessManager(this);
    connect(reqSaveAuthPhoto,SIGNAL(finished(QNetworkReply*)),SLOT(replySaveAuthPhotoFinished(QNetworkReply*)));

    reqCheckPhoto = new QNetworkAccessManager(this);
    connect(reqCheckPhoto,SIGNAL(finished(QNetworkReply*)),SLOT(replyCheckPhotoFinished(QNetworkReply*)));


    reqSubmitPhoto = new QNetworkAccessManager(this);
    connect(reqSubmitPhoto,SIGNAL(finished(QNetworkReply*)),SLOT(replySubmitPhotoFinished(QNetworkReply*)));

    ui->leIentify->setPlaceholderText(tr("请输入本人身份证号码"));

    connect(ui->pbLogin, SIGNAL(clicked()), this, SLOT(loginReqAndCheck()));
    //added by xuhongneng @20170824 begin
    connect(ui->pbModifyID, SIGNAL(clicked()), this, SLOT(modifyId()));
    //added by xuhongneng @20170824 end

#ifdef _WINXP
    m_pCamera = new QNBExCamera(640, 480, this);
    m_pCamera->initialize();

    connect(m_pCamera, SIGNAL(Captured(QImage)), this, SLOT(saveImage(QImage)));
#else
    if(QNBConfig::getInstance()->getCameraDevice().isEmpty()) {
        qDebug()<<"will open this camera";
        camera = new QCamera(this);
        if(camera == NULL) {
           qDebug()<<"new a camera failed";
        }

        QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
        foreach (const QCameraInfo &cameraInfo, cameras) {
            qDebug()<<"a camera:"<<cameraInfo.deviceName();
            //if (cameraInfo.deviceName() == "mycamera")
            //    camera = new QCamera(cameraInfo);
        }

    } else {
        qDebug()<<"will open this camera: "<<QNBConfig::getInstance()->getCameraDevice().toLatin1();
        camera = new QCamera(QNBConfig::getInstance()->getCameraDevice().toLatin1(), this);
    }

    if(camera != NULL)
    {
      connect(camera, SIGNAL(error(QCamera::Error)), this, SLOT(printCameraError(QCamera::Error)));
    }


    //added by xuhongneng @20170826 begin
    m_pCaptureVideoFrame = new CCaptureVideoFrame;
    m_pCaptureVideoFrame->setLabel(ui->lbPhotoFrame);
    m_pCaptureVideoFrame->setSource(camera);
    //added by xuhongneng @21070826 end

 //   m_pVideoItem = new QGraphicsVideoItem;
 //   m_pVideoItem->setSize(QSizeF(640, 480));

  //  m_pScence = new QGraphicsScene(this);
 //   m_pGraphicsView = new QGraphicsView(m_pScence);

  //  m_pScence->addItem(m_pVideoItem);
  //  camera->setViewfinder(m_pVideoItem);
  //  m_pVideoItem->setTransform(QTransform().rotate(-360));
 //   ui->photoImageView->addWidget(m_pGraphicsView);


    //removed by xuhongneng @20170826 begin
    //viewfinder=new QCameraViewfinder(this);
    //qDebug()<<"width: "<<viewfinder->size().width();
    //qDebug()<<"height: "<<viewfinder->size().height();
    //removed by xuhongneng @20170826 end

    imageCapture=new QCameraImageCapture(camera);
    connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(saveImage(int,QImage)));

 //removed by xuhongneng @20170825 begin
 /*
    viewfinder->setFixedWidth(640);
    viewfinder->setFixedHeight(480);

    ui->photoImageView->addWidget(viewfinder);

    camera->setViewfinder(viewfinder);
*/

    camera->start();
    //removed by xuhongneng @20170825 end

#endif

#ifdef _WINXP
    m_pCaptureToVideoTimer = new QTimer();
    connect(m_pCaptureToVideoTimer, SIGNAL(timeout()), this, SLOT(captureImageToVideo()));

    m_pCaptureToVideoTimer->start(40);
#endif


    ui->lbName->setText(tr("温馨提醒（请实人、实名、实时上网）"));
    ui->lbTip->setText(tr("请将脸部放在摄像机框内，无法登陆请联系服务台"));
    ui->lbOrg->setText(tr("本系统版权所有，技术支持：华码(厦门)物联科技有限公司"));


//    QShortcut *key=new QShortcut(QKeySequence(Qt::Key_Return),this);//创建一个快捷键"Key_Return"键
//   connect(key,SIGNAL(activated()),this,SLOT(loginReqAndCheck()));
//    connect(key,SIGNAL(activated()),this,SLOT(modifyId()));


//    this->setWindowOpacity(1);
//    this->setWindowFlags(Qt::FramelessWindowHint);
    //this->setAttribute(Qt::WA_TranslucentBackground);
    //removed by xuhongneng @20170804
    setAutoFillBackground(false);  //这个不设置的话就背景变黑
//    setWindowFlags(Qt::FramelessWindowHint);
//    setAttribute(Qt::WA_TranslucentBackground,true);
//setWindowModality(Qt::ApplicationModal);


    this->showFullScreen();
    //SetWindowLong((HWND)winId(), GWL_EXSTYLE, GetWindowLong((HWND)winId(), GWL_EXSTYLE));

    //added by xuhongneng @20170804 start
    QPalette pal =this->palette();
    //pal.setColor(QPalette::Background, QColor(255,255,255)); //黑色
    pal.setBrush(QPalette::Background, QPixmap("caolv.bmp"));
    this->setPalette( pal );
    //this->setStyleSheet("background-image:url(:touming.jpg);");
    //added by xuhongneng @20170804 end

    //removed by xuhongneng @20170817 begin tempory
    //removed by xuhongneng @20170829 begin
    keepTopWindowsInit();
    //removed by xuhongneng @20170817 end

    loginMsgBox.hide();
    serverErrorMsgBox.hide();
    checkPhotoErrorMsgBox.hide();

}

QNBLogin::~QNBLogin()
{
    if(m_pCheckDaemonProcessTimer)
    {
        m_pCheckDaemonProcessTimer->stop();
        delete m_pCheckDaemonProcessTimer;
        m_pCheckDaemonProcessTimer = NULL;
    }

    delete ui;
    delete m_translator;

    delete m_pCheckPhotoExe;

    m_pCheckPhotoByIntervalTimer->stop();
    delete m_pCheckPhotoByIntervalTimer;

    m_pSubmitPhotoByIntervalTimer->stop();
    delete m_pSubmitPhotoByIntervalTimer;

    m_pCheckStatusTimer->stop();
    delete m_pCheckStatusTimer;

    if(m_pVideoItem != NULL)
    {
       delete m_pVideoItem;
       m_pVideoItem = NULL;
    }

    if(m_pScence != NULL){
        delete m_pScence;
        m_pScence = NULL;
    }

    if(m_pGraphicsView != NULL)
    {
        delete m_pGraphicsView;
        m_pGraphicsView = NULL;
    }

    if(reply) {
        delete reply;
    }

    if (reply2) {
        delete reply2;
    }

    if (reply3) {
        delete reply3;
    }

 #ifdef _WINXP
    if(m_pCamera != NULL)
    {
        m_pCamera->deinitialize();
        delete m_pCamera;
        m_pCamera = NULL;
    }

    if(m_pCaptureToVideoTimer != NULL)
    {
        m_pCaptureToVideoTimer->stop();
        delete m_pCaptureToVideoTimer;
        m_pCaptureToVideoTimer = NULL;
    }

 #else
    if(m_pCaptureVideoFrame != NULL) {
        m_pCaptureVideoFrame->stop();
        delete m_pCaptureVideoFrame;
        m_pCaptureVideoFrame = NULL;
    }

    if(imageCapture != NULL)
    {
        delete imageCapture;
        imageCapture = NULL;
    }

    if(camera != NULL) {
      camera->stop();

    //removed by xuhongneng @20170825 begin
    //viewfinder->close();
    //removed by xuhongneng @20170825 end


      delete camera;
      camera = NULL;
    }


    //removed by xuhongneng @20170825 begin
    //delete viewfinder;
    //removed by xuhongneng @20170825 end
#endif

    delete reqLogin;
    delete reqSaveAuthPhoto;

#if HIDE_KEY
    unHook();
#endif
}

void QNBLogin::modifyId()
{
    ui->leIentify->setEnabled(true);
    ui->leIentify->setFocus();
    ui->leIentify->setText(tr(""));

    //this->setFocusPolicy(Qt::NoFocus);
}

void QNBLogin::loginReqAndCheck()
{
    QString strIdentify = ui->leIentify->text().trimmed();
    if(strIdentify.isEmpty()) {
        QMessageBox::information(this, "提示", "请输入身份证号码");
        return;
    } else if (strIdentify.length() != 18) {
        QMessageBox::information(this, "提示", "身份证号码应该为18位");
        return;
    }

    if(!m_bVerifying) {
        m_bVerifying = true;
#ifdef _WINXP
        m_pCamera->capture();
#else
        imageCapture->capture();
#endif
//    if (QNBUserInfo::getInstance()->mstrIdentify.isEmpty()
//            || QNBUserInfo::getInstance()->mstrIdentify != strIdentify
//            || QNBUserInfo::getInstance()->mstrAuthPhoto.isEmpty()) {

        mstrIdentify = strIdentify;
        QString strUrl = QNBConfig::getInstance()->getServerHttpController()+"/getauthphoto.html?identify="+mstrIdentify+"&clientid="+QNBUserInfo::getInstance()->mstrClientId;
        QNetworkRequest req(strUrl);




        qDebug()<<"no error....."<<strUrl;

        if(reply) {
            disconnect(reply, 0, 0, 0);
            delete reply;
        }

        reply = reqLogin->get(req);

        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(reqLoginError(QNetworkReply::NetworkError)));

//    } else if(!QNBUserInfo::getInstance()->mstrIdentify.isEmpty()
//              && !QNBUserInfo::getInstance()->mstrAuthPhoto.isEmpty()){

//        bCheckPhotoRunning = true;
//    }
    } else {
         QMessageBox::information(this, "提示", "正在验证中，请稍后...");
    }
}

void QNBLogin::replyFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        qDebug()<<"no error.....";
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串
        qDebug()<<result;

        //todo  get auth photo,then check!!!
        if(!analyzeLoginResp(bytes)) {
            qDebug()<<" analyze login data error! login failed.";
            return;
        }

        reqAuthPhotoFile();

    } else {
        qDebug() << "222replyFinished:  " << reply->error() << " " <<reply->errorString();


        QNBUserInfo::getInstance()->mstrIdentify.clear();
        QNBUserInfo::getInstance()->mstrAuthPhoto.clear();
        QNBUserInfo::getInstance()->mstrRealPhoto.clear();
        if(loginMsgBox.isHidden()) {
             qDebug() << "r222eplyFinished:  " << reply->error() << " " <<reply->errorString();
            loginMsgBox.setParent(this);
            loginMsgBox.setWindowTitle(tr("错误"));
            loginMsgBox.setText(tr("身份证尚未注册?"));
            loginMsgBox.exec();
        }
    }

    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<status_code;
}

void QNBLogin::reqLoginError(QNetworkReply::NetworkError errorCode)
{
    qDebug() << "reqLoginError  errorCode: " << (int)errorCode;
\

    QNBUserInfo::getInstance()->mstrIdentify.clear();
    QNBUserInfo::getInstance()->mstrAuthPhoto.clear();
    QNBUserInfo::getInstance()->mstrRealPhoto.clear();

    if(loginMsgBox.isHidden()) {
        //loginMsgBox.setParent(this);
        SetWindowPos((HWND)loginMsgBox.winId(),HWND_TOPMOST,loginMsgBox.pos().x(),
                            loginMsgBox.pos().y(),loginMsgBox.width(),loginMsgBox.height(),SWP_SHOWWINDOW);
        loginMsgBox.setWindowTitle(tr("错误"));
        loginMsgBox.setText(tr("服务器响应错误."));
        loginMsgBox.exec();
    }

    m_bVerifying = false;
    return;
}

void QNBLogin::reqCheckPhotoSimilarError(QNetworkReply::NetworkError errorCode)
{
    qDebug() << "reqLoginError  errorCode: " << (int)errorCode;

    if(!serverErrorMsgBox.isActiveWindow()) {
        //serverErrorMsgBox.setParent(this);
        SetWindowPos((HWND)serverErrorMsgBox.winId(),HWND_TOPMOST,serverErrorMsgBox.pos().x(),
                            serverErrorMsgBox.pos().y(),serverErrorMsgBox.width(),serverErrorMsgBox.height(),SWP_SHOWWINDOW);
        serverErrorMsgBox.setWindowTitle(tr("提示"));
        serverErrorMsgBox.setText(tr("图像对比相似度太低."));
        serverErrorMsgBox.exec();
    }

    return;
}

void QNBLogin::reqSubmitPhotoError(QNetworkReply::NetworkError errorCode)
{
    qDebug() << "Submit Photo error,  errorCode: " << (int)errorCode;

//    if(!serverErrorMsgBox.isActiveWindow()) {
//        serverErrorMsgBox.setWindowTitle(tr("Error"));
//        serverErrorMsgBox.setText(tr("Submit photo error."));
//        serverErrorMsgBox.exec();
//    }

    return;
}

void QNBLogin::printCameraError(QCamera::Error errorCode)
{
    qDebug() << "get Camera error,  errorCode: " << errorCode;
}

void QNBLogin::reqGetAuthPhotoError(QNetworkReply::NetworkError errorCode)
{
    qDebug() << "get Auth Photo error,  errorCode: " << (int)errorCode;

    if(!serverErrorMsgBox.isActiveWindow()) {
        //serverErrorMsgBox.setParent(this);
        SetWindowPos((HWND)serverErrorMsgBox.winId(),HWND_TOPMOST,serverErrorMsgBox.pos().x(),
                            serverErrorMsgBox.pos().y(),serverErrorMsgBox.width(),serverErrorMsgBox.height(),SWP_SHOWWINDOW);
        serverErrorMsgBox.setWindowTitle(tr("Error"));
        serverErrorMsgBox.setText(tr("Get auth photo error."));
        serverErrorMsgBox.exec();
    }

    return;
}

void QNBLogin::replySaveAuthPhotoFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        qDebug()<<"no error.....";
        QByteArray bytes = reply->readAll();  //获取字节


        QString strAuthPhotoFile = QNBUtls::getAuthDataDir();
        strAuthPhotoFile += QDir::separator();
        strAuthPhotoFile += QNBUserInfo::getInstance()->mstrIdentify;
        strAuthPhotoFile += PHOTO_FILE_SUFFIX;

        QNBUserInfo::getInstance()->mstrLocalAuthPhoto = strAuthPhotoFile;

        QFile file(strAuthPhotoFile);
        if (file.exists()) {
            file.remove();
        }
        file.open(QIODevice::WriteOnly);
        file.write(bytes);
        file.close();

        bCheckPhotoRunning = true;

        //added by xuhongneng @20170821 begin

        //added by xuhongneng @20170821 end

        captureImage();

    } else {
        qDebug() << "replyFinished:  " << reply->error() << " " <<reply->errorString();

//        QMessageBox msgBox;
//        msgBox.setText(tr("the auth photo is not exist?"));
//        msgBox.exec();
    }

    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<status_code;

}


bool QNBLogin::analyzeLoginResp(QByteArray data)
{
    bool bRet = false;
    if(!data.isEmpty()) {
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(data, &json_error);
        qDebug()<<"analyzeLoginResp   "<<data;
        if(json_error.error == QJsonParseError::NoError)
        {
            if(parse_doucment.isObject())
            {
                QJsonObject obj = parse_doucment.object();
                QString strAuthPhoto = QNBUtls::getStringValue(obj, "auth_photo", "");
                qDebug()<<strAuthPhoto;
                if(!strAuthPhoto.isEmpty())
                {
                    QNBUserInfo::getInstance()->mstrIdentify = mstrIdentify;
                    QNBUserInfo::getInstance()->mstrAuthPhoto = strAuthPhoto;

                    bRet = true;
                }
            }
        }
    }

    return bRet;
}


void QNBLogin::reqAuthPhotoFile()
{
    if (QNBUserInfo::getInstance()->mstrAuthPhoto.isEmpty()) {
        qDebug()<<"auth photo path is empty, req auth photo failed.";
        return;
    }

    //"/netbar/"后续可能要去掉。
    QString strUrl = HTTP_POTOCOL +QNBConfig::getInstance()->getServerIP()+ "/netbar/"  "/public/"+ QNBUserInfo::getInstance()->mstrAuthPhoto;
    //QString strUrl = HTTP_POTOCOL HTTP_HOST QNBUserInfo::getInstance()->mstrAuthPhoto;
    QNetworkRequest req(strUrl);

    qDebug()<<"auth photo path:"<<strUrl;

    if(reply2) {
        disconnect(reply2, 0, 0, 0);
        delete reply2;
    }

    reply2 = reqSaveAuthPhoto->get(req);

    connect(reply2, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(reqGetAuthPhotoError(QNetworkReply::NetworkError)));


}

void QNBLogin::captureImage()
{
#ifdef _WINXP
    m_pCamera->capture();
#else
    imageCapture->capture();
#endif
}

#ifdef _WINXP
void QNBLogin::saveImage(QImage image)
{
    this->saveImage(0, image);
}

#endif

void QNBLogin::saveImage(int , QImage image)
{
    QString strPhotoPath = QNBUtls::getTmpDataDir();

    if(strPhotoPath.isEmpty()) {

    }

    strPhotoPath += QDir::separator();
    strPhotoPath += QString("%1").arg(QNBUtls::curTime());
    strPhotoPath += PHOTO_FILE_SUFFIX;

    qDebug()<<"capture login  save img..."<<strPhotoPath;

    if(image.save(strPhotoPath)) {
        mstrCapPhoto = strPhotoPath;
        QNBUserInfo::getInstance()->mstrRealPhoto = mstrCapPhoto;
    } else {
        QNBUserInfo::getInstance()->mstrRealPhoto.clear();
        qDebug()<<"capture login photo and save failed."<<strPhotoPath;
    }

    if (bCheckPhotoRunning) {

        bCheckPhotoRunning = false;

        //身份证，认证图片无需更新。直接比对图片
        checkPhoto();
    }

}

bool QNBLogin::savePhotoBase64(QByteArray arr, const QString& filepath)
{
    QFile capfile(filepath);
    capfile.open(QIODevice::WriteOnly);

    QDataStream in(&capfile);
    in.writeBytes(arr, arr.length());
    capfile.close();


    return true;
}

QByteArray QNBLogin::getPhotoBase64(const QString& filepath)
{
    QFile capfile(filepath);
    capfile.open(QIODevice::ReadOnly);
    int  file_len = capfile.size();

    QDataStream in(&capfile);
    char *m_cap = new char[file_len];
    in.readRawData( m_cap, file_len);
    capfile.close();


    QByteArray arr = QByteArray( m_cap, file_len );

    delete m_cap;

    return arr.toBase64();
}

void QNBLogin::runCheckPhotoExe()
{
    qDebug()<<"runCheckPhotoExe running...";
    //QString strExe = "E:/QtDev/NetBarClient/ConsoleApplication1.exe";
    QString strExe = "E:/QtDev/NetBarClient/checkphoto/ConsoleApplication1.exe";
    strExe += " ";
    strExe += QNBUserInfo::getInstance()->mstrLocalAuthPhoto;
    strExe += " ";
    strExe += QNBUserInfo::getInstance()->mstrRealPhoto;

    //m_pCheckPhotoExe->execute(strExe, QStringList() << QNBUserInfo::getInstance()->mstrLocalAuthPhoto << QNBUserInfo::getInstance()->mstrRealPhoto);
    //m_pCheckPhotoExe->start(strExe);
    QProcess::execute(strExe);

    qDebug()<<"runCheckPhotoExe running333..."<<strExe;
    //m_pCheckPhotoExe->waitForFinished();

    qDebug()<<"runCheckPhotoExe running222...";

}

#ifdef _WINXP
void QNBLogin::captureImageToVideo()
{
    QImage image;
    m_pCamera->capture(CAPTURED_FOR_VIDEO);
    image = m_pCamera->getImage();
    QImage mirrored = image.mirrored(true, false);
    ui->lbPhotoFrame->setPixmap(QPixmap::fromImage(mirrored));
    //ui->lbPhotoFrame->setPixmap(QPixmap::fromImage(image));
    ui->lbPhotoFrame->update();
    this->update();
}
#endif

void QNBLogin::readCheckPhotoResult(int exitCode)
{
    qDebug()<<"readCheckPhotoResult running...";
    //if(exitCode == 0) {

        qDebug()<<"........."<<m_pCheckPhotoExe->readAll();

    //}
}

bool QNBLogin::checkPhoto()
{
    if (mstrCapPhoto.isEmpty()) {
        qDebug() << "check photo failed, the cap photo is empty.";
        return false;
    }

    QUrl url = QUrl("http://127.0.0.1:8080/web/");
    if(!QNBConfig::getInstance()->getCheckPhotoServerUrl().isEmpty()) {
        url = QUrl(QNBConfig::getInstance()->getCheckPhotoServerUrl());
    }


    qDebug()<<"check photo path:"<<url;

    QNetworkRequest request(url);

    QString strAuthPhotoContent = QNBUserInfo::getInstance()->mstrLocalAuthPhoto;
    QString strRealPhotoContent = QNBUserInfo::getInstance()->mstrRealPhoto;
    if (QNBConfig::getInstance()->checkPhotoUseBase64()) {
            QByteArray capArr = getPhotoBase64(strAuthPhotoContent);
            QByteArray authArr = getPhotoBase64(strRealPhotoContent);

            strAuthPhotoContent = authArr ;
            strRealPhotoContent = capArr;
    }

    qDebug() << "check photo.....";

    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=----WebKitFormBoundaryXAZF4WB0RGNfySBl");

    QString strContent2 = "------WebKitFormBoundaryXAZF4WB0RGNfySBl\r\nContent-Disposition: form-data; name=\"img1\"";
    strContent2 += "\r\n\r\n";
    strContent2 += strAuthPhotoContent;

    QString strContent3 = "------WebKitFormBoundaryXAZF4WB0RGNfySBl\r\nContent-Disposition: form-data; name=\"img2\"";
    strContent3 += "\r\n\r\n";
    strContent3 += strRealPhotoContent;

    QString strContent = strContent2.toLatin1();
    strContent += "\r\n";
    strContent += strContent3.toLatin1();
    strContent += "\r\n";
    strContent += "------WebKitFormBoundaryXAZF4WB0RGNfySBl--\r\n";

    if(reply3) {
        disconnect(reply3, 0,0,0);\
        delete reply3;
    }
#if PASS_CHECK_PHOTO_DEBUG
    reply3 = reqCheckPhoto->post( request , strContent.toLatin1());
    connect(reply3, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(reqCheckPhotoSimilarError(QNetworkReply::NetworkError)));
#else
    QNBUserInfo::getInstance()->miRealCheckPhotoSimilar = 90;
    login();
#endif
    return true;
}



void QNBLogin::replyCheckPhotoFinished(QNetworkReply *reply)
{
#if PASS_CHECK_PHOTO_DEBUG
    if(reply->error() == QNetworkReply::NoError)
    {
         QByteArray data = reply->readAll();  //获取字节

        qDebug()<<" replyCheckFinished no error....."<<data;

        if(!data.isEmpty()) {
            QJsonParseError json_error;
            QJsonDocument parse_doucment = QJsonDocument::fromJson(data.trimmed(), &json_error);
            qDebug()<<"replyCheckFinished   "<<data;
            if(json_error.error == QJsonParseError::NoError)
            {
                if(parse_doucment.isObject())
                {
                    QJsonObject obj = parse_doucment.object();
                    QString strStatus = QNBUtls::getStringValue(obj, "status", "500");
                    qDebug()<<strStatus;
                    if(!strStatus.isEmpty() && strStatus.toInt() == 200) {
                        QString strCode = QNBUtls::getStringValue(obj, "sim", "0");

                        if(!strCode.isEmpty()) {
                             QNBUserInfo::getInstance()->miRealCheckPhotoSimilar = strCode.toInt();
                             if (QNBUserInfo::getInstance()->isCheckPhotoPass()) {
                                   if(QNBUserInfo::getInstance()->mLoginStatus != ENUM_LOGIN) {
                                       login();
                                   }
                                   QNBUserInfo::getInstance()->miCheckPhotoErrorCount = 0;
                                   qDebug() << " check photo pass!  ";
                             } else {
                                  if(QNBUserInfo::getInstance()->mLoginStatus == ENUM_LOGIN) {
                                      QNBUserInfo::getInstance()->miCheckPhotoErrorCount++;
                                      qDebug() << " check photo not pass!  "<<QNBUserInfo::getInstance()->miCheckPhotoErrorCount;
                                  } else if(QNBUserInfo::getInstance()->mLoginStatus == ENUM_LOGIN_BEGIN) {

                                      QNBUserInfo::getInstance()->miLoginCheckPhotoErrorCount++;
                                      if (QNBUserInfo::getInstance()->miLoginCheckPhotoErrorCount > LOGIN_CHECK_PHOTO_ERROR_MAX_COUNT) {

                                          QNBUserInfo::getInstance()->miLoginCheckPhotoErrorCount  = 0;
                                          //msgBox.setParent(this);
                                          SetWindowPos((HWND)msgBox.winId(),HWND_TOPMOST,msgBox.pos().x(),msgBox.pos().y(),msgBox.width(),msgBox.height(),SWP_SHOWWINDOW);
                                          msgBox.setWindowTitle(tr("提示"));
                                         // msgBox.setText(tr("Verify faile, please go to counter and register again!"));
                                          msgBox.setText(tr("验证失败，请到前台重新注册!"));
                                          msgBox.exec();
                                      } else {
                                          SetWindowPos((HWND)msgBox.winId(),HWND_TOPMOST,msgBox.pos().x(),msgBox.pos().y(),msgBox.width(),msgBox.height(),SWP_SHOWWINDOW);
                                          msgBox.setWindowTitle(tr("提示"));
                                          msgBox.setText(tr("只能本人上网【相似度低】，请重新验证!"));
                                          msgBox.exec();
                                      }

                                      qDebug() << " check photo not pass!  "<<QNBUserInfo::getInstance()->miCheckPhotoErrorCount;

                                  } else if(QNBUserInfo::getInstance()->mLoginStatus == ENUM_LOGIN_END && m_bVerifying) {
                                      //msgBox.setParent(this);
                                      SetWindowPos((HWND)msgBox.winId(),HWND_TOPMOST,msgBox.pos().x(),msgBox.pos().y(),msgBox.width(),msgBox.height(),SWP_SHOWWINDOW);
                                      msgBox.setWindowTitle(tr("提示"));
                                      msgBox.setText(tr("请实人上网【相似度低】，请重新验证!"));
                                      msgBox.exec();
                                  }
                             }


                             qDebug() << " check photo, similar: "<<strCode;
                        }
                    } else {
                        if (checkPhotoErrorMsgBox.isHidden()) {
                            QNBUserInfo::getInstance()->mstrRealPhoto.clear();

                            //checkPhotoErrorMsgBox.setParent(this);
                            SetWindowPos((HWND)checkPhotoErrorMsgBox.winId(),HWND_TOPMOST,checkPhotoErrorMsgBox.pos().x(),
                                                checkPhotoErrorMsgBox.pos().y(),checkPhotoErrorMsgBox.width(),checkPhotoErrorMsgBox.height(),SWP_SHOWWINDOW);
                            checkPhotoErrorMsgBox.setWindowTitle(tr("提示"));
                            checkPhotoErrorMsgBox.setText(tr("验证失败，请重新验证!"));
                            checkPhotoErrorMsgBox.exec();
                        }
                    }
                }
            }
        }

    } else {
        qDebug() << "replyCheckPhotoFinished:  " << reply->error() << " " <<reply->errorString();

    }

    //removed by xuhongneng @20170824 begin
    {
       int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
       qDebug()<<"replyCheckFinished"<<status_code;
    }
    //removed by xuhongneng @02170824 end
    //
#else

    QNBUserInfo::getInstance()->miRealCheckPhotoSimilar = 90;
    login();

#endif

    m_bVerifying = false;
}

void QNBLogin::replySubmitPhotoFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray data = reply->readAll();  //获取字节

        qDebug()<<" replySubmitPhotoFinished no error....."<<data;

        if(!data.isEmpty()) {
            QJsonParseError json_error;
            QJsonDocument parse_doucment = QJsonDocument::fromJson(data, &json_error);
            qDebug()<<"replySubmitPhotoFinished   "<<data;
            if(json_error.error == QJsonParseError::NoError)
            {
                if(parse_doucment.isObject())
                {
                    QJsonObject obj = parse_doucment.object();
                    QString strStatus = QNBUtls::getStringValue(obj, "code", "-1");
                    qDebug()<<strStatus;
                    if(!strStatus.isEmpty() && strStatus.toInt() == 0) {
                        qDebug()<<"replySubmitPhotoFinished successfully   ";
                    }
                }
            }
        }
    }
}


void QNBLogin::checkNetBarDaemonExist()
{
    BOOL bFind;
    bFind = FALSE;

//    camera->start();

   // update();

    unsigned long aProcesses[1024], cbNeeded, cProcesses;
    if( !EnumProcesses(aProcesses,sizeof(aProcesses),&cbNeeded) )
    {
        qDebug()<<"枚举进程失败";
        return;
    }

    cProcesses = cbNeeded / sizeof(unsigned long);

    for(unsigned int i = 0; i < cProcesses; i++)
    {
        if(aProcesses[i] == 0)
        {
            continue;
        }

        //获取已存在的进程对象句柄
        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, aProcesses[i]);

        if (hProcess != NULL) {
            wchar_t buffer[50];
            memset(buffer, 0, sizeof buffer);
            GetModuleBaseName(hProcess, 0, buffer, 50);
            CloseHandle(hProcess);
            qDebug()<<QString::fromWCharArray(buffer);

            if (QString::fromWCharArray(buffer) == QString::fromWCharArray(SVCHOST_NAME_FORK_W))
            {
               qDebug()<<"找到进程"<<SVCHOST_NAME_FORK;
               bFind = TRUE;
               break;
            }
        }
    }


    if(!bFind) { //打开进程
        QProcess Process;
        char szCmd[256] = {0};
        _snprintf_s(szCmd, 255, " %s %s", TEMP_FILE_NAME, SVCHOST_NAME_FORK);
        if(!Process.startDetached(szCmd))
        {
             qDebug()<<"进程["<<SVCHOST_NAME_FORK<<"]不存在，startDetached:试图打开进程失败,原因:"<<Process.errorString();
        }

        Sleep(10);
    } else {
            qDebug()<<"进程["<<SVCHOST_NAME_FORK<<"]存在,无需再运行";
    }

  return;
}

/*
 * 间隔性提交图片
 */
void QNBLogin::submitPhotoByInterval()
{

    if (QNBUserInfo::getInstance()->mLoginStatus == ENUM_FORCE_LOGIN && QNBUserInfo::getInstance()->mstrRealPhoto.isEmpty()) {
        qDebug()<<"real photo file is empty or not login status, submit photo failed ";
        return;
    }
    qDebug()<<"submitPhotoByInterval  running.";

//    QNBUserInfo::getInstance()->miRealCheckPhotoSimilar = 40;
//    captureImage();//是否延迟？



    QFile file(QNBUserInfo::getInstance()->mstrRealPhoto);
    file.open(QIODevice::ReadOnly);
    int  file_len = file.size();

    QDataStream in(&file);
    char *m_buf = new char[file_len];
    in.readRawData( m_buf, file_len);
    file.close();
    qDebug()<<"flie name: "<<QNBUserInfo::getInstance()->mstrRealPhoto;
    qDebug()<<"flie size: "<<file_len;

    QUrl url = QNBConfig::getInstance()->getServerHttpController()+ "/" "submitRealInfo";


    QNetworkRequest request( url );

    qDebug()<<url;

    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=----WebKitFormBoundaryXAZF4WB0RGNfySBl");

    QString strHeader = "------WebKitFormBoundaryXAZF4WB0RGNfySBl";
    strHeader += "\r\n";
    strHeader += "Content-Disposition: form-data; name=\"image\"; filename=\"NetSain.png\"";
    strHeader += "\r\n";
    strHeader += "Content-Type: image/png";
    strHeader += "\r\n\r\n";

    QString strContent2 = "------WebKitFormBoundaryXAZF4WB0RGNfySBl\r\nContent-Disposition: form-data; name=\"identify\"";
    strContent2 += "\r\n\r\n";
    strContent2 += QNBUserInfo::getInstance()->mstrIdentify;

    QString strContent3 = "------WebKitFormBoundaryXAZF4WB0RGNfySBl\r\nContent-Disposition: form-data; name=\"clientid\"";
    strContent3 += "\r\n\r\n";
    strContent3 += QNBUserInfo::getInstance()->mstrClientId;

    QByteArray arr = QByteArray( m_buf, file_len );

    QByteArray strContent = strHeader.toLatin1();
    strContent += arr;
    strContent += "\r\n";
    strContent += strContent2.toLatin1();
    strContent += "\r\n";
    strContent += strContent3.toLatin1();
    strContent += "\r\n";
    strContent += "------WebKitFormBoundaryXAZF4WB0RGNfySBl--\r\n";

    if(reply4) {
        disconnect(reply4, 0, 0, 0);
        delete reply4;
    }

    reply4 = reqSubmitPhoto->post( request , strContent);

    connect(reply4, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(reqSubmitPhotoError(QNetworkReply::NetworkError)));

    delete m_buf;
    qDebug() << "checkPhotoByInterval "<<QNBConfig::getInstance()->checkPhotoInterval();
}

/*
 * 间隔性比对图片
 */
void QNBLogin::checkPhotoByInterval()
{
    if (QNBUserInfo::getInstance()->mLoginStatus == ENUM_FORCE_LOGIN && QNBUserInfo::getInstance()->mstrRealPhoto.isEmpty()) {
        qDebug()<<"real photo file is empty or not login status, submit photo failed ";
        return;
    }

    qDebug()<<"checkPhotoByInterval  running.";


    QNBUserInfo::getInstance()->miRealCheckPhotoSimilar = 40;
    captureImage();//是否延迟？

    checkPhoto();
}

void QNBLogin::checkTimer(QTimer *timer, int interval)
{
//    camera->start();

    int sec = timer->interval()/1000;
    if (sec != interval && interval > 0) {
        timer->stop();
        timer->setInterval(interval*1000);
        timer->start();
    }
}

//bool QNBLogin::isTopWindows()
//{

//    return GetWindowLong(hTaslManWnd, GWL_EXSTYLE) & WS_EX_TOPMOST;
//}

void QNBLogin::keepTopWindowsInit()
{
    HMODULE hUser32;

    SetWindowPos((HWND)this->winId(),HWND_TOPMOST,this->pos().x(),this->pos().y(),this->width(),this->height(),SWP_SHOWWINDOW);

    hUser32 = ::GetModuleHandle(L"user32");
    GetTaskmanWindow = (PROCGETTASKMANWND)GetProcAddress(hUser32,"GetTaskmanWindow");

    hTaslManWnd = GetTaskmanWindow();
}

void QNBLogin::keepTopWindows(bool isShow)
{
    if(isShow) {
        qDebug()<<"test11110000";
        if(!ShowWindow(GetParent(hTaslManWnd),SW_HIDE)) {

            //SetWindowPos((HWND)this->winId(),HWND_TOPMOST,this->pos().x(),this->pos().y(),this->width(),this->height(),SWP_SHOWWINDOW);
            qDebug()<<"test1111";
        }
        this->show();
        //added by xuhongneng @20170824 begin
        //added by xuhongneng @20170824 end
    } else {
        qDebug()<<"test00001111";
        if(!ShowWindow(GetParent(hTaslManWnd),SW_SHOW)) {

            qDebug()<<"test000";
            //SetWindowPos((HWND)this->winId(),HWND_TOPMOST,this->pos().x(),this->pos().y(),this->width(),this->height(),SWP_HIDEWINDOW);
        }
        this->hide();
        //added by xuhongneng @20170824 begin
         ui->leIentify->setEnabled(false);
         ui->pbLogin->setFocus();
        //added by xuhongneng @20170824 end
    }
}

typedef HWND (WINAPI *PROCGETTASKMANWND)(void);
void QNBLogin::checkRunningStatus()
{
    m_pCheckStatusTimer->stop();

    checkTimer(m_pCheckPhotoByIntervalTimer, QNBConfig::getInstance()->checkPhotoInterval());
    checkTimer(m_pSubmitPhotoByIntervalTimer, QNBConfig::getInstance()->submitPhotoInterval());

    switch(QNBUserInfo::getInstance()->mLoginStatus)
    {
    case ENUM_LOGIN_BEGIN:
        qDebug()<<"ENUM_LOGIN_BEGIN";
        if (QNBUserInfo::getInstance()->isForceLogin()) {
            ui->leIentify->setText(QNBUserInfo::getInstance()->mstrIdentify);
            if(login()) {
                keepTopWindows(false);
            }
        } else {
            keepTopWindows(true);
        }
        break;
    case ENUM_LOGIN:
        qDebug()<<"ENUM_LOGIN";
        //后台是否强制登出
//        if (QNBUserInfo::getInstance()->isForceLogout()) {
//            QNBUserInfo::getInstance()->mForceAction = ENUM_FORCE_UNKNOW;

//            ui->leIentify->setText("");
//            logout();
//            keepTopWindows(true);
//            qDebug()<<"isForceLogout";
//        }

//        //心跳超时，则退出
//        else if (QNBUserInfo::getInstance()->isHeartTimeOut()) {
//            logout();
//            keepTopWindows(true);
//            qDebug()<<"isHeartTimeOut";
//        }

//        //达到一定比对错误次数，则退出
//        //else
//        else
        if (QNBUserInfo::getInstance()->isUp2CheckPhotoErrorMaxCount()) {
            logout();
            keepTopWindows(true);
            qDebug()<<"isUp2CheckPhotoErrorMaxCount";
        } else {
            keepTopWindows(false);
        }
        break;
    case ENUM_LOGIN_END:
        //删除老用户数据
        if (QNBUserInfo::getInstance()->isDeleteUserDataTimeOut()) {
            QNBUserInfo::getInstance()->deleteUserData();
            QNBUserInfo::getInstance()->setLoginStatus(ENUM_LOGIN_END);
        }
        keepTopWindows(true);
        break;
    default:
        break;
    }

    m_pCheckStatusTimer->start(QNBConfig::getInstance()->loopCheckLoginStatusInterval()*1000);
}


bool QNBLogin::login()
{
    if (!QNBUserInfo::getInstance()->isCheckPhotoPass()) {
        qDebug()<<"login -- check photo failed...";
        return false;
    }

    qDebug()<<"login -- check photo ok...";

    if (!m_pSubmitPhotoByIntervalTimer->isActive()) {
        m_pSubmitPhotoByIntervalTimer->start(QNBConfig::getInstance()->submitPhotoInterval()*1000);
    }

    if (!m_pCheckPhotoByIntervalTimer->isActive()) {
        m_pCheckPhotoByIntervalTimer->start(QNBConfig::getInstance()->checkPhotoInterval()*1000);
    }

    this->hide();
//    if(!this->isHidden()) {
//        this->hide();
//    }

    if(!mstrIdentify.isEmpty() && QNBUserInfo::getInstance()->mstrIdentify != mstrIdentify) {
        QNBUserInfo::getInstance()->mstrIdentify = this->mstrIdentify;
    }

    QNBUserInfo::getInstance()->setLoginStatus(ENUM_LOGIN);
    QNBUserInfo::getInstance()->miHeartTime =
            QNBUserInfo::getInstance()->miLoginTime = QNBUtls::curTime();

#if HIDE_KEY
    unHook();
#endif

    return true;
}


void QNBLogin::logout()
{
    m_pSubmitPhotoByIntervalTimer->stop();
    m_pCheckPhotoByIntervalTimer->stop();

    this->show();
//    if(this->isHidden()) {
//        this->show();
//    }
#if HIDE_KEY
    setHook();
#endif
    QNBUserInfo::getInstance()->setLoginStatus(ENUM_LOGIN_END);
    QNBUserInfo::getInstance()->miLogoutTime = QNBUtls::curTime();

    //QNBUserInfo::getInstance()->mstrRealPhoto.clear();
    QNBUserInfo::getInstance()->miCheckPhotoErrorCount = 0;
}

void QNBLogin::deleteUserData()
{
    QNBUserInfo::getInstance()->setLoginStatus(ENUM_LOGIN_BEGIN);
    QNBUserInfo::getInstance()->deleteUserData();
    QNBUserInfo::getInstance()->clear();
}


void QNBLogin::InitUiByLanguage(const QString strLanguage)
{
    if (strLanguage.isEmpty())
    {
        return;
    }

    QString strLanguageFile;
    if (strLanguage.compare("zh") == 0)
    {
        strLanguageFile = qApp->applicationDirPath() + "/nb_zh_CN.qm";
       // strLanguageFile = qApp->applicationDirPath() + QString("/../../DeviceTemplateDesigner/DeviceTemplateDesigner_zh_CN.qm");
    }
    else if (strLanguage.compare("en") == 0)
    {
        strLanguageFile = qApp->applicationDirPath() + "/DeviceTemplateDesigner_en_CN.qm";
      //  strLanguageFile = qApp->applicationDirPath() + QString("/../../DeviceTemplateDesigner/DeviceTemplateDesigner_en_CN.qm");
    }

    if (QFile(strLanguageFile).exists())
    {
         qDebug() << "[houqd] authclient language file "<<strLanguageFile;
        m_translator->load(strLanguageFile);
        qApp->installTranslator(m_translator);
        this->ui->retranslateUi(this);
    }
    else
    {
        qDebug() << "[houqd] authclient language file does not exists ..."<<strLanguageFile;
    }
}

/**********************************************************
  不用调用dll就可以执行的全局钩子示例:
  只留下F12做为程序退出,屏蔽键盘和鼠标,测试时请注意
  ********************************************************/

HHOOK keyHook=NULL;
HHOOK mouseHook=NULL;

//键盘钩子过程
LRESULT CALLBACK keyProc(int nCode,WPARAM wParam,LPARAM lParam )
{
    //在WH_KEYBOARD_LL模式下lParam 是指向KBDLLHOOKSTRUCT类型地址
    KBDLLHOOKSTRUCT *pkbhs = (KBDLLHOOKSTRUCT *) lParam;
    //如果nCode等于HC_ACTION则处理该消息，如果小于0，则钩子子程就必须将该消息传递给 CallNextHookEx
    if(nCode == HC_ACTION){
        if(pkbhs->vkCode == VK_ESCAPE && GetAsyncKeyState(VK_CONTROL)& 0x8000 && GetAsyncKeyState(VK_SHIFT)&0x8000){
                    qDebug() << "Ctrl+Shift+Esc";
        } else if(pkbhs->vkCode == VK_DELETE && GetAsyncKeyState(VK_CONTROL)& 0x8000 && GetAsyncKeyState(VK_SHIFT)&0x8000){
            qDebug() << "Ctrl+Shift+Del";
            return 1;
        } else if(pkbhs->vkCode == VK_DELETE && GetAsyncKeyState(VK_CONTROL)& 0x8000 && GetAsyncKeyState(VK_MENU)&0x8000){
            qDebug() << "Ctrl+ALT+Del";
            return 1;
        } else if(pkbhs->vkCode == VK_ESCAPE && GetAsyncKeyState(VK_CONTROL) & 0x8000){
            qDebug() << "Ctrl+Esc";
        }else if(pkbhs->vkCode == VK_TAB && pkbhs->flags & LLKHF_ALTDOWN){
            qDebug() << "Alt+Tab";
        }else if(pkbhs->vkCode == VK_ESCAPE && pkbhs->flags &LLKHF_ALTDOWN){
            qDebug() << "Alt+Esc";
        }else if(pkbhs->vkCode == VK_LWIN || pkbhs->vkCode == VK_RWIN){
            qDebug() << "LWIN/RWIN";
        }else if(pkbhs->vkCode == VK_F4 && pkbhs->flags & LLKHF_ALTDOWN){
            qDebug() << "Alt+F4";
        }
        if(pkbhs->vkCode == VK_F12)
        {
#if HIDE_KEY
    unHook();

#endif

            QNBLogin::getInstance()->keepTopWindows(false);
            QNBLogin::clearResource();
            qApp->quit();
        }

        /*键盘 字母上面那排数字*/
        if((pkbhs->vkCode >= 0x30 && pkbhs->vkCode <= 0x39) || pkbhs->vkCode == 0x58) {
            return 0;
        }

        /*数字键盘上面那排数字*/
        if(pkbhs->vkCode >= 0x60 && pkbhs->vkCode <= 0x69) {
            return 0;
        }

        /*返回删除键、数字键盘上的Num Lock键*/
        if(pkbhs->vkCode == VK_BACK || pkbhs->vkCode == VK_NUMLOCK ) {
            return 0;
        }

        /*查看assic 对照表，包含数字，字母，特殊字符*/
        if(pkbhs->vkCode >= 32 && pkbhs->vkCode <= 127) {
            return 0;
        }

        /*左右两边的Shift键 */
        if(pkbhs->vkCode == VK_LSHIFT || pkbhs->vkCode == VK_RSHIFT ) {
            return 0;
        }

        if(pkbhs->vkCode == VK_RETURN ) {
            return 0;
        }

        return 1;//返回1表示截取消息不再传递,返回0表示不作处理,消息继续传递
    }

    return CallNextHookEx(keyHook, nCode, wParam, lParam);
}

//鼠标钩子过程
LRESULT CALLBACK mouseProc(int nCode,WPARAM wParam,LPARAM lParam )
{

    return 1;
}
//卸载钩子
static void unHook()
{
    UnhookWindowsHookEx(keyHook);



    QNBLockCtrlAltDel::TaskScreen(true);
    UnhookWindowsHookEx(mouseHook);

}
//安装钩子,调用该函数即安装钩子
static void setHook()
{

    //这两个底层钩子,不要DLL就可以全局
    //底层键盘钩子
    keyHook =SetWindowsHookEx( WH_KEYBOARD_LL,keyProc,GetModuleHandle(NULL),0);

    QNBLockCtrlAltDel::TaskScreen(false);
    //底层鼠标钩子
    //mouseHook =SetWindowsHookEx( WH_MOUSE_LL,mouseProc,GetModuleHandle(NULL),0);
}

////添加注册评比Ctrl+Alt+del
//void TaskManager(bool flag)
//{
//    QSettings *settings = new QSettings(TASKMANAGER, QSettings::NativeFormat);
//    if(flag){
//        settings->setValue("DisableTaskMgr", "1");
//    }else{
//        settings->remove("DisableTaskMgr");
//    }
//    delete settings;
//}

//void MainWindow::on_pushButton_clicked()
//{
//    //注册 钩子
//    setHook();
//    qDebug() << "0000000";
//}


//void MainWindow::on_pushButton_2_clicked()
//{
//    // 销毁 钩子
//    unHook();
//    qDebug() << "33333333";
//}

//void MainWindow::on_pushButton_3_clicked()
//{
//    TaskManager(true);
//}

//void MainWindow::on_pushButton_4_clicked()
//{
//    TaskManager(false);
//}

//void MainWindow::on_pushButton_5_clicked()
//{
//    if(ui->pushButton_5->text() == QString::fromLocal8Bit("隐藏任务栏")){
//        task=FindWindow(L"Shell_TrayWnd",NULL);
//        ShowWindow(task,SW_HIDE);
//        ui->pushButton_5->setText(QString::fromLocal8Bit("显示任务栏"));
//    }else{
//        ShowWindow(task,SW_SHOW);
//        ui->pushButton_5->setText(QString::fromLocal8Bit("隐藏任务栏"));
//    }
//}


